package com.erpanderp.wam.cm.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;

import org.primefaces.component.datatable.DataTable;
import org.primefaces.context.RequestContext;
import org.primefaces.model.UploadedFile;

import com.erpanderp.wam.adm.model.entity.SAPERPModule;
import com.erpanderp.wam.adm.model.service.SAPERPModuleDAO;
import com.erpanderp.wam.tm.model.entity.RecruitmentProfile;
import com.erpanderp.wam.tm.model.entity.RecruitmentVendor;
import com.erpanderp.wam.tm.model.service.RecruitmentProfileDAO;
import com.erpanderp.wam.tm.model.service.VendorRegistrationDAO;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.ValidationUtil;

@ManagedBean
@ViewScoped
public class UploadCVDBProfilesBean implements Serializable{


	private static final long serialVersionUID = 1L;
	private HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	private WAMUser wamUser = (WAMUser) session.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
	
	private UploadedFile file;
	private String fileName;
	private File realPath;
	private boolean FORM_VALID;
	private DataTable assignedNewResourcesTable;
	private String selectedTechnology;
	
	private RecruitmentProfile recruitmentProfile = new RecruitmentProfile();
	private RecruitmentVendor recruitmentVendor=new RecruitmentVendor();
	
	private SAPERPModuleDAO saperpModuleDAO = new SAPERPModuleDAO();
	private RecruitmentProfileDAO recruitmentProfileDAO=new RecruitmentProfileDAO();
	private VendorRegistrationDAO vendorRegistrationDAO=new VendorRegistrationDAO();
	
	private List<RecruitmentProfile> recruitmentProfiles = new ArrayList<RecruitmentProfile>();
	private Map<String, String> technologiesMap = new HashMap<String, String>();
	private List<SAPERPModule> technologies = new ArrayList<SAPERPModule>();

	public UploadCVDBProfilesBean() {
		
		technologies = saperpModuleDAO.getSAPERPModules();
		for (SAPERPModule saperpModule : technologies) {
			technologiesMap.put(saperpModule.getSAPERPModule(),	saperpModule.getSAPERPModule());
		}
		
	}
	
	public void confirmationAction(ActionEvent e){
		
		if (recruitmentProfiles.size() > 0 ) {
			RequestContext.getCurrentInstance().execute("confirmation.show();");
		}else{
			FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "There are no resources/profiles to upload.", ""));
		}
    }	
	// ACTIONS FOR CREATING NEW RESOURCE
	public String createAnotherResourceAction() {				
		validateForm();
		if (FORM_VALID) {
			try{
				RecruitmentProfile isProfileExists=null;
				 ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();
				 fileName = file.getFileName();				 
				 
				 Pattern pattern = Pattern.compile("[^a-zA-Z\\s]");
				 Matcher matcher = pattern.matcher(selectedTechnology);
				 String technology = matcher.replaceAll("");
				 
				 File sss= new File(extContext.getRealPath("//RRFResumes//"+technology+"//"));
				 boolean isDirectoryCreated = sss.mkdir();
				 setRealPath(new File(sss+"//"+file.getFileName()));
								
					System.out.println("=============11111111================");
					
					recruitmentProfile.setTechnology(selectedTechnology);
					recruitmentProfile.setUploadFilePath("\\"+technology+"\\"+fileName);//File related
					recruitmentProfile.setFileSize(file.getSize());//File related
					recruitmentProfile.setFile(file);//File related
					setRecruitmentVendor(vendorRegistrationDAO.getRecruitmentVendorByVendorId(1l));
					recruitmentProfile.setProfileCurrentStatus("Open");//STATUS
					recruitmentProfile.setManagerRecommendationStatus("Not Available");
					recruitmentProfile.setInterviewer1FeedbackStatus("Not Available");
					recruitmentProfile.setInterviewer2FeedbackStatus("Not Available");
					//recruitmentProfile.setInterviewerLevel("Level1-Inprocess");
					recruitmentProfile.setCreateDate(new Date());
					recruitmentProfile.setUploadedBy(wamUser.getEmployee());
					recruitmentProfile.setCreatedBy(CommonLookup.CREATEDBY_DEVELOPER_TEXT);
					recruitmentProfile.setStatus(CommonLookup.STATUS_ACTIVE);
					
					
					isProfileExists=recruitmentProfileDAO.isRecruitmentProfileExists(recruitmentProfile.getCandidateEmail(),recruitmentProfile.getCandidateMobileNumber());
					
					if(isProfileExists != null){
						FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "This profile(E-Mail Id/ContactNo) is already exists.", ""));
					}else{
						recruitmentProfiles.add(recruitmentProfile); //ALL RECORDS LIST						
					}
					
					recruitmentProfile = new RecruitmentProfile();
			
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}	
	
	//DELETE RESORCE FROM TABLE LIST		
	public void removeRecruitmentResource(ActionEvent e){
		RecruitmentProfile selectedResource = (RecruitmentProfile) assignedNewResourcesTable.getRowData();		
		recruitmentProfiles.remove(selectedResource);
	}
	
	public String uploadResourcesAction() {		
		try{	
			 if (recruitmentProfiles.size() > 0 ) {
				for(RecruitmentProfile recruitmentProfile : recruitmentProfiles){
					try{					
							ExternalContext extContext=FacesContext.getCurrentInstance().getExternalContext();
							File rootPath= new File(extContext.getRealPath("//RRFResumes//"));
						    FileOutputStream fileOutputStream = new FileOutputStream(rootPath+recruitmentProfile.getUploadFilePath(),true);
							byte[] buffer = new byte[1024*1024*10];		//10MB
							int bulk;						
						    InputStream inputStream = recruitmentProfile.getFile().getInputstream();
							while (true) {
								bulk = inputStream.read(buffer);
									if (bulk < 0) {
									 break;
									}
								fileOutputStream.write(buffer, 0, bulk);
								fileOutputStream.flush();
						   }
						 fileOutputStream.close();
						 inputStream.close();	
						 
						}catch (Exception e) {
							e.printStackTrace();
						}					
					}
					
					recruitmentProfileDAO.saveRecruitmentProfiles(recruitmentProfiles);
					recruitmentProfiles = new ArrayList<RecruitmentProfile>();
					recruitmentProfile = new RecruitmentProfile();
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "Resources are uploaded successfully.", ""));
				}else{
					FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_INFO, "There are no resources/profiles to upload.", ""));
				}
			
			}catch (Exception e) {
				e.printStackTrace();
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Failed to upload Resources.", e.getMessage()));
			}
		
			return null;
		}
		
	// VALIDATIONS
	private void validateForm() {
		FORM_VALID = true;
	
	    if(file.getFileName() == null || file.getFileName().equals("") ){
	    	FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Upload Resume cannot be empty", ""));
	    	FORM_VALID = false;
	    }else{
	    	String fileName =file.getFileName();
			 String fileExtention = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
			 
			 if (fileExtention.equalsIgnoreCase("docx") || fileExtention.equalsIgnoreCase("doc") || fileExtention.equalsIgnoreCase("pdf") || fileExtention.equalsIgnoreCase("odt") )
	         {
				System.out.println("File should be any one of above specified format");

	         }else{
	        	 FORM_VALID = false;
				 FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Invalid file type.File name should be in .docx,.doc,.pdf or .odt", ""));
	         }
		 
	    }
		
		if (ValidationUtil.isEmpty(recruitmentProfile.getCandidateName(), " Candidate Name", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
		}
		if (ValidationUtil.isEmpty(recruitmentProfile.getCandidateEmail(), " Candidate Email", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
		} else {
			System.out.println("EMAIL ENTERED");
			if (ValidationUtil.isEmailValid(recruitmentProfile.getCandidateEmail(), "Candidate Email", null,
					FacesContext.getCurrentInstance()) != null) {
				FORM_VALID = false;
			} 
		}
		if (ValidationUtil.isEmpty(recruitmentProfile.getCandidateMobileNumber(), " Candidate Contact", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
		}
		if (ValidationUtil.isEmpty(recruitmentProfile.getCandidateExperience(), "Total Experience", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
		}else{
			int totalExp = 0;
			
			try
			{
				totalExp = Integer.parseInt(recruitmentProfile.getCandidateExperience());
			}
			catch (NumberFormatException nfe)
			{
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Please enter numeric values in the experience.", ""));
				FORM_VALID = false;
				System.out.println("==========INSIDE CATCH BLOCK======NumberFormatException=====");
			}
			
			
			if(totalExp > 50){
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Experience should be less than 50 years.", ""));
				FORM_VALID = false;
			}else if((totalExp < 50)){
				System.out.println("EXP IS WITH IN RANGE 50 years====");
			}else{
				FacesContext.getCurrentInstance().addMessage("", new FacesMessage(FacesMessage.SEVERITY_WARN, "Please enter numeric values in the experience.", ""));
				FORM_VALID = false;
			}
		}
		if (ValidationUtil.isEmpty(recruitmentProfile.getCandidateCurrentLocation(), "Candidate Location",
				null, FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
		}				
	}		
	//GETTERS AND SETTERS
	public WAMUser getWamUser() {
		return wamUser;
	}

	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}

	public UploadedFile getFile() {
		return file;
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public File getRealPath() {
		return realPath;
	}

	public void setRealPath(File realPath) {
		this.realPath = realPath;
	}

	public RecruitmentProfile getRecruitmentProfile() {
		return recruitmentProfile;
	}

	public void setRecruitmentProfile(RecruitmentProfile recruitmentProfile) {
		this.recruitmentProfile = recruitmentProfile;
	}

	public List<RecruitmentProfile> getRecruitmentProfiles() {
		return recruitmentProfiles;
	}

	public void setRecruitmentProfiles(List<RecruitmentProfile> recruitmentProfiles) {
		this.recruitmentProfiles = recruitmentProfiles;
	}

	public boolean isFORM_VALID() {
		return FORM_VALID;
	}

	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}

	public DataTable getAssignedNewResourcesTable() {
		return assignedNewResourcesTable;
	}

	public void setAssignedNewResourcesTable(DataTable assignedNewResourcesTable) {
		this.assignedNewResourcesTable = assignedNewResourcesTable;
	}

	public String getSelectedTechnology() {
		return selectedTechnology;
	}

	public void setSelectedTechnology(String selectedTechnology) {
		this.selectedTechnology = selectedTechnology;
	}

	public Map<String, String> getTechnologiesMap() {
		return technologiesMap;
	}

	public void setTechnologiesMap(Map<String, String> technologiesMap) {
		this.technologiesMap = technologiesMap;
	}

	public RecruitmentVendor getRecruitmentVendor() {
		return recruitmentVendor;
	}

	public void setRecruitmentVendor(RecruitmentVendor recruitmentVendor) {
		this.recruitmentVendor = recruitmentVendor;
	}

}
